package com.atguigu.edu.controller.front;

import com.atguigu.edu.client.OrdersClient;
import com.atguigu.edu.entity.frontvo.CourseFrontVo;
import com.atguigu.edu.entity.Course;
import com.atguigu.edu.entity.chapter.ChapterVo;
import com.atguigu.edu.entity.frontvo.CourseWebVo;
import com.atguigu.edu.service.ChapterService;
import com.atguigu.edu.service.CourseService;
import com.atguigu.utils.JwtUtils;
import com.atguigu.utils.R;
import com.atguigu.utils.vo.CourseWebVoOrder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
//@CrossOrigin
@Api(description = "前台课程管理",value = "前台课程管理")
public class CourseFrontController {

    @Resource
    private CourseService courseService;
    @Resource
    private ChapterService chapterService;
    @Resource
    private OrdersClient ordersClient;
    //分页条件查询展示课程信息
    @PostMapping("/pageInfo/{page}/{limit}")
    public R pageInfo(@PathVariable("page")long page,@PathVariable("limit")long limit,
                      @RequestBody(required = false) CourseFrontVo courseFrontVo){
        Page<Course> pageInfo=new Page(page,limit);
        Map<String,Object> map=courseService.getListByPage(pageInfo,courseFrontVo);
        return R.ok().data(map);
    }
    //获取课程的详细信息和章节小节
    @GetMapping("/getCourseInfo/{courseId}")
    public R getCourseInfo(@PathVariable("courseId")String courseId, HttpServletRequest request){
        //根据课程id课程基本信息
        CourseWebVo courseWebVo=courseService.getCourseWebInfo(courseId);
        //获取课程的所有章节和小节
        List<ChapterVo> chapterVideoList = chapterService.getAllChapterVideo(courseId);
        //判断课程是否购买
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(memberId==null){
            return R.ok().data("courseWebVo",courseWebVo)
                    .data("chapterVideoList",chapterVideoList).data("isBuy",false);
        }
        boolean buyCourse = ordersClient.isBuyCourse(courseId, memberId);
        return R.ok().data("courseWebVo",courseWebVo)
                .data("chapterVideoList",chapterVideoList).data("isBuy",buyCourse);
    }
    //根据课程id得到课程信息
    @GetMapping("/getCourseWebVoInfo/{courseId}")
    public CourseWebVoOrder getCourseWebVoInfo(@PathVariable("courseId")String courseId){
        CourseWebVo courseWebInfo = courseService.getCourseWebInfo(courseId);
        CourseWebVoOrder courseWebVoOrder=new CourseWebVoOrder();
        BeanUtils.copyProperties(courseWebInfo,courseWebVoOrder);
        return courseWebVoOrder;
    }
}
